<template>
    <div class="login-wrap">
<!--  rules对应验证对象    -->
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="login-form" >
        <h2 class="login-h2">管理员登录</h2>
<!--   prop对应字段名     -->
        <el-form-item  prop="userName" label="用户名">
          <el-input type="text" v-model="ruleForm.userName" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item  prop="passWord" label="密码">
          <el-input type="password" v-model="ruleForm.passWord" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>

<script>

export default {
  data () {
    return {
      ruleForm: {
        userName: '',
        passWord: ''
      },
      // 验证对象，与整个form的rules属性保持一致
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }, // 失去焦点时验证
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 11, message: '长度在 6 到 11 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        // 如果通过前端验证才发送请求
        if (valid) {
          this.$axios({
            url: 'test/login/login',
            method: 'post',
            data: this.ruleForm
          }).then(result => {
            if (result.data !== '') {
              // 如何验证是否从登陆进入？cookie session
              // 但是前后端分离没有，只有token(令牌，验证身份)
              // 拿到登陆的数据后，需要将令牌保存下来(localStorage中)
              // token是后端返回回来的
              sessionStorage.setItem('tk', result.data)
              // localStorage.setItem('tk', result.data) // 设置只需要键值对
              // console.log(localStorage.getItem('tk')) 查看token值
              // 编程式导航进行路由跳转，跳到首页
              this.$router.push({
                path: '/'
              })
              // 弹出消息提示
              this.$message({
                message: '登陆成功！',
                type: 'success'
              })
            } else {
              this.$message.error('登陆失败！')
              return false
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
  .login-wrap {
    background-color: #607d8b;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .login-h2 {
    text-align: center;
  }
  .login-form {
    background-color: #fff;
    width: 400px;
    padding: 30px;
    border-radius: 5px;
  }
  .login-btn {
    width: 100%;
  }
</style>
